const officegen = require('officegen')
const fs = require('fs')
const axios = require('axios')
const { chengyudata } = require("./data")
// console.log(chengyudata)
// Create an empty Word object:
let docx = officegen('docx')

// Officegen calling this function after finishing to generate the docx document:
//创建一个word文件
docx.on('finalize', function (written) {
  console.log(
    'Finish to create a Microsoft Word document.'
  )
})

// Officegen calling this function to report errors:
docx.on('error', function (err) {
  console.log(err)
})

new Promise((resolve, reject) => {
  fs.readFile('./chengyu.json', (err, data) => {
    if (err) {
      return console.log(err)
    }
    let alldata = JSON.parse(data.toString())
    resolve(alldata)
  })
}).then(res => {

  for (let index = 0; index < chengyudata.length; index++) {
    res.forEach(item => {
      for (const key in item) {
        // console.log(key)  //所有的成语名字
        if (key == chengyudata[index]) {
          var pObj = docx.createP();
          pObj.addText(`${key}: ${item[key]}`, { font_face: '宋体', font_size: 15 })
        }
      }
    });
  }

  let out = fs.createWriteStream('成语.docx')
  out.on('error', function (err) {
    console.log(err)
  })
  docx.generate(out)
})




// Create a new paragraph:
// let pObj = docx.createP()
// pObj.addText('已有的内容', { font_face: '宋体', font_size: 12 })
// docx.putPageBreak()//换页

// Let's generate the Word document into a file:

// let out = fs.createWriteStream('成语.docx')

// out.on('error', function (err) {
//   console.log(err)
// })

// // Async call to generate the output file:
// docx.generate(out)